<template>
  <div class="permission-list">
    <!-- 搜索和操作区域 -->
    <div class="operation-area">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="权限名称">
          <el-input v-model="searchForm.name" placeholder="请输入权限名称" clearable />
        </el-form-item>
        <el-form-item label="权限编码">
          <el-input v-model="searchForm.code" placeholder="请输入权限编码" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="operation-buttons">
        <el-button type="primary" @click="handleAdd">添加权限</el-button>
      </div>
    </div>

    <!-- 表格区域 -->
    <el-table
      v-loading="loading"
      :data="permissionList"
      border
      style="width: 100%"
    >
      <el-table-column type="index" width="50" />
      <el-table-column prop="code" label="权限编码" width="180" />
      <el-table-column prop="name" label="权限名称" width="150" />
      <el-table-column prop="description" label="权限描述" min-width="200" />
      <el-table-column label="使用角色数" width="100">
        <template #default="{ row }">
          <el-tag type="info">{{ row.roleCount || 0 }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
          <el-button 
            type="danger" 
            link 
            @click="handleDelete(row)"
            :disabled="row.roleCount > 0"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页区域 -->
    <div class="pagination-area">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        :total="total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑权限' : '添加权限'"
      width="500px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="权限编码" prop="code">
          <el-input 
            v-model="formData.code" 
            placeholder="请输入权限编码"
            :disabled="isEdit"
          />
        </el-form-item>
        <el-form-item label="权限名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入权限名称" />
        </el-form-item>
        <el-form-item label="权限描述" prop="description">
          <el-input
            v-model="formData.description"
            type="textarea"
            :rows="3"
            placeholder="请输入权限描述"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit" :loading="submitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getPermissionList } from '@/api/admin'

const loading = ref(false)
const submitting = ref(false)
const dialogVisible = ref(false)
const isEdit = ref(false)
const permissionList = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const formRef = ref(null)

// 获取权限列表
const fetchPermissionList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      pageSize: pageSize.value,
      ...searchForm.value
    }
    const res = await getPermissionList(params)
    const permissions = Array.isArray(res) ? res : []
    permissionList.value = permissions
    total.value = permissionList.value.length
  } catch (error) {
    console.error('获取权限列表失败：', error)
    ElMessage.error(error.message || '获取权限列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索表单
const searchForm = ref({
  name: '',
  code: '',
  group: ''
})

// 表单数据
const formData = ref({
  code: '',
  name: '',
  description: '',
  group: ''
})

// 表单验证规则
const rules = {
  code: [
    { required: true, message: '请输入权限编码', trigger: 'blur' },
    { pattern: /^[a-z][a-z0-9_:]*$/, message: '权限编码只能包含小写字母、数字、下划线和冒号，且必须以字母开头', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入权限名称', trigger: 'blur' },
    { min: 2, max: 64, message: '长度在 2 到 64 个字符', trigger: 'blur' }
  ],
  description: [
    { max: 255, message: '长度不能超过 255 个字符', trigger: 'blur' }
  ],
  group: [
    { required: true, message: '请选择权限分组', trigger: 'change' }
  ]
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchPermissionList()
}

// 重置搜索
const resetSearch = () => {
  searchForm.value = {
    name: '',
    code: '',
    group: ''
  }
  handleSearch()
}

// 添加权限
const handleAdd = () => {
  isEdit.value = false
  formData.value = {
    code: '',
    name: '',
    description: '',
    group: ''
  }
  dialogVisible.value = true
}

// 编辑权限
const handleEdit = (row) => {
  isEdit.value = true
  formData.value = { ...row }
  dialogVisible.value = true
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    submitting.value = true

    if (isEdit.value) {
      await updatePermission(formData.value.id, formData.value)
      ElMessage.success('修改成功')
    } else {
      await createPermission(formData.value)
      ElMessage.success('添加成功')
    }

    dialogVisible.value = false
    fetchPermissionList()
  } catch (error) {
    console.error('提交失败：', error)
    ElMessage.error(error.message || '提交失败，请检查表单')
  } finally {
    submitting.value = false
  }
}

// 删除权限
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该权限吗？此操作不可恢复！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await deletePermission(row.id)
    ElMessage.success('删除成功')
    fetchPermissionList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除权限失败：', error)
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 分页大小改变
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchPermissionList()
}

// 页码改变
const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchPermissionList()
}

onMounted(() => {
  fetchPermissionList()
})
</script>

<style lang="scss" scoped>
.permission-list {
  .operation-area {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: flex-start;

    .search-form {
      flex: 1;
    }

    .operation-buttons {
      margin-left: 20px;
    }
  }

  .pagination-area {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style> 